<template>
  <div id="radio" ref="radioContainer">
    <div class="radio-station" v-for="station in displayedStations" :key="station.month" ref="stationContainers">
      <div class="month">{{ formatMonthDisplay(station.month) }}</div>

      <div class="radio-item" v-for="item in station.items" :key="item.id">
        <div class="bgimg" :style="{ backgroundImage: 'url(' + item.cover + ')' }" @click="openDetail(item)">
          <div class="radio-logo">
            <span>YUNQI</span>
            <i></i>
            <span class="radio-issue">{{ item.volume }}</span>
          </div>
          <div class="radio-title">{{ item.title }}</div>
          <div class="play-btn" @click.stop="togglePlay(item)" :class="{ 'playing': isItemPlaying(item) }"></div>
        </div>

        <div class="radio-bottom">
          <div class="user">
            <div class="avatar" :style="{ backgroundImage: 'url(' + item.author.web_url + ')' }"></div>
            <div class="user-name">{{ item.author.user_name }}</div>
          </div>
          <div class="like">
            <i class="one-icon" :class="item.isLiked ? 'one-icon-liked' : 'one-icon-like'"
              @click="toggleLike(item)"></i>
            <span>{{ item.like_count }}</span>
          </div>
          <i class="recommend-iconfont icon-share"></i>
        </div>
      </div>
    </div>

    <div v-if="isLoading" class="loading">加载中...</div>

    <RadioDetail :radioId="currentRadioId" :isVisible="isDetailVisible" :currentDetailItem="currentDetailItem"
      @close="closeDetail" />

  </div>
</template>

<script>
import { getRadioListByMonth } from '@/api/api';
import { mapState, mapActions } from 'vuex';
import RadioDetail from '@/components/RadioDetail.vue';

export default {
  components: {
    RadioDetail
  },
  data() {
    return {
      allStations: [], // 存储所有月份的电台数据
      displayedStations: [], // 当前显示在页面上的电台数据
      currentEarliestMonth: '', // 当前加载的最早月份
      isLoading: false, // 是否正在加载数据
      loadLock: false, // 防止重复加载的锁
      isDetailVisible: false,  // 控制详情页显示
      currentDetailItem: null, // 当前详情页对应的电台
      currentRadioId: null, // 当前电台ID
    }
  },

  created() {
    // 初始化音频实例
    this.initAudio();
    // 初始化：获取最近3个月的数据
    const months = this.getRecentMonths(3);
    this.currentEarliestMonth = months[months.length - 1];
    months.forEach(month => this.loadMonthData(month));
  },

  mounted() {
    // 添加滚动监听，实现滚动加载更多
    this.$refs.radioContainer.addEventListener('scroll', this.handleScroll);
  },

  beforeDestroy() {
    this.$refs.radioContainer.removeEventListener('scroll', this.handleScroll);
  },

  computed: {
    // 映射Vuex状态到组件
    ...mapState('audio', {
      currentAudio: state => state.currentAudio,
      isPlaying: state => state.isPlaying
    }),
    // 详情页播放状态（根据当前音频是否为详情页音频判断）
    detailAudioPlaying() {
      return this.isPlaying && this.currentAudio?.id === this.currentDetailItem?.id
    }
  },

  methods: {
    // 映射Vuex actions到组件
    ...mapActions('audio', ['initAudio', 'togglePlay', 'pauseAudio']),

    // 播放状态判断方法
    isItemPlaying(item) {
      return this.isPlaying && this.currentAudio?.id === item.id
    },

    // 获取最近几个月的月份字符串数组
    getRecentMonths(count) {
      const months = [];
      const today = new Date();
      for (let i = 0; i < count; i++) {
        const year = today.getFullYear();
        let month = today.getMonth() + 1 - i;
        if (month <= 0) {
          month += 12;
          today.setFullYear(year - 1);
        }
        const monthStr = `${year}-${month.toString().padStart(2, '0')}`;
        months.push(monthStr);
      }
      return months
    },

    // 获取指定月份的上一个月
    getPreviousMonth(month) {
      const [year, monthNum] = month.split('-').map(Number);
      let prevYear = year;
      let prevMonth = monthNum - 1;
      if (prevMonth < 1) {
        prevMonth = 12;
        prevYear--;
      }
      return `${prevYear}-${prevMonth.toString().padStart(2, '0')}`;
    },

    // 加载指定月份的电台数据
    loadMonthData(month) {
      // 避免重复加载同一月份
      if (this.allStations.some(s => s.month === month)) return

      this.isLoading = true
      getRadioListByMonth(month)
        .then(res => {
          // 为每个电台项添加播放和点赞状态
          const formattedItems = res.data.map(item => ({
            ...item,
            isPlaying: false,
            isLiked: false,
            audioLoaded: false
          }))

          // 添加到数据集并按月份降序排序
          this.allStations.push({ month, items: formattedItems });
          this.displayedStations = [...this.allStations]
            .sort((a, b) => b.month.localeCompare(a.month));
        })
        .catch(err => console.error(`加载${month}数据失败:`, err))
        .finally(() => {
          this.isLoading = false;
          this.loadLock = false;
        });
    },

    // 格式化月份显示，如"05月"
    formatMonthDisplay(month) {
      return `${month.split('-')[1]}月`;
    },

    // 处理滚动事件，实现滚动到底部加载更多
    handleScroll() {
      if (this.isLoading || this.loadLock) return

      const container = this.$refs.radioContainer;
      const lastStation = this.$refs.stationContainers?.[this.$refs.stationContainers.length - 1];

      if (!lastStation) return

      // 检测是否滚动到底部附近
      const lastStationBottom = lastStation.offsetTop + lastStation.offsetHeight;
      const scrollBottom = container.scrollTop + container.clientHeight;

      // 提前200px触发加载
      if (lastStationBottom <= scrollBottom + 200) {
        this.loadLock = true;
        const nextMonth = this.getPreviousMonth(this.currentEarliestMonth);
        this.currentEarliestMonth = nextMonth;
        this.loadMonthData(nextMonth);
      }
    },

    // 切换点赞状态
    toggleLike(item) {
      if (item.isLiked) {
        item.like_count--;
      } else {
        item.like_count++;
      }
      item.isLiked = !item.isLiked;
    },

    // 打开详情页方法
    openDetail(item) {
      this.currentDetailItem = item; // 记录当前详情页对应的音频项
      this.currentRadioId = item.id; // 设置当前电台ID
      this.isDetailVisible = true;

      // 如果有正在播放的音频，先暂停
      if (this.currentAudio) {
        this.pauseAudio();
      }
      // 播放当前详情页对应的音频
      this.togglePlay(this.currentDetailItem);
    },

    // 关闭详情页方法
    closeDetail() {
      this.isDetailVisible = false;
      this.currentRadioId = null;
      this.currentDetailItem = null;
    },


  }
}
</script>

<style scoped lang="less">
@import url('../assets/recommend-icon/iconfont.css');

#radio {
  min-height: 100vh;
  padding: 3vh 10px 12vh;
  box-sizing: border-box;
  background-color: #fff;
  overflow-y: auto;
  height: 100vh;
}

.radio-station {

  .month {
    width: 100%;
    padding: 10px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    color: #ccc;
    margin-bottom: 5px;

    &::before {
      content: '';
      width: 45%;
      height: 1px;
      transform: scaleY(0.2);
      background-color: #b9b9b9;
      margin-right: 5px;
    }

    &::after {
      content: '';
      width: 45%;
      height: 1px;
      transform: scaleY(0.2);
      background-color: #b9b9b9;
      margin-left: 5px;
    }
  }

  .radio-item {
    height: 25vh;
    margin-bottom: 15px;
    border-radius: 8px;
    position: relative;

    .audio-player {
      display: none;
    }

    .bgimg {
      height: 80%;
      color: #fff;
      border-radius: 8px;
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;

      .radio-logo {
        position: absolute;
        left: 2%;
        top: 2%;
        font-size: 10px;
        display: flex;
        align-items: center;
        gap: 2px;
      }

      .radio-issue {
        font-size: 8px;
        font-weight: 100;
      }

      .radio-title {
        position: absolute;
        bottom: 25%;
        left: 2%;
        font-size: 14px;
        font-weight: 100;
      }

      .play-btn {
        right: 5%;
        bottom: 25%;
        width: 20px;
        height: 20px;
      }
    }

    .radio-bottom {
      height: 20%;
      padding: 10px 5px;
      box-sizing: border-box;
      display: flex;
      color: #ddd;
      font-size: 8px;
      align-items: center;
      justify-content: space-between;

      .user {
        display: flex;
        align-items: center;
        gap: 3px;
        height: 100%;

        .avatar {
          height: 100%;
          aspect-ratio: 1/1;
          border-radius: 50%;
          background-size: contain;
          background-position: center;
          background-repeat: no-repeat;
        }
      }

      .like {
        display: flex;
        align-items: center;
        gap: 3px;

        i {
          font-size: 14px;
        }
      }

      >i {
        font-size: 14px;
      }
    }

  }
}

.play-btn {
  display: block;
  position: absolute;
  z-index: 5;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  background-image: url(../assets/play.svg);

  &.playing {
    background-image: url(../assets/pause.svg);
  }
}

.loading {
  text-align: center;
  padding: 15px;
  font-size: 12px;
  color: #999;
}
</style>